var STATE_INITIAL = 0;
var STATE_PLAYING = 1;
var STATE_RESULTS = 2;

var state_;
var metadata_;
var participants_;

var gameState = STATE_INITIAL;
var firstPlayer = false;

function updateLocalParticipantsData(participants) {
    participants_ = participants;
}

function stateChanged(event) {
    console.log('state changed. updating...');
    state_ = event.state;
    metadata_ = event.metadata;

    var addedKeys = event.addedKeys;

    for (var i = 0; i < addedKeys.length; i++) {
        var added = addedKeys[i];
        console.log('added to state: ' + added.key);
        if (added.key == 'letters') {
            addedLetters();
        }
        else if (added.key.indexOf('words_') == 0) {
            addedResults(added.key, eval('(' + added.value + ')'));
        }
    }
}

function addedLetters() {
    gapi.hangout.data.clearValue('words_' + gapi.hangout.getLocalParticipantId());
    clearResults();
    letters = eval('(' + state_.letters + ')');
    populateBoard();
    startTimer();
    displayBoard();
}

function addedResults(added, words) {
    console.log('added result from: ' +  gapi.hangout.getParticipantById(added.substring(6)).person.displayName);
    var result = {
        id: added.substring(6),
        name: gapi.hangout.getParticipantById(added.substring(6)).person.displayName,
        words: words
    };
    results.push(result);
    if (results.length == participants_.length) {
        score(results);
        writeResults(results);
    }
}

function gameEnd() {
    console.log('timer expired');
    var delta = {};
    var resultKey = 'words_' + gapi.hangout.getLocalParticipantId();
    delta[resultKey] = JSON.stringify(words);
    gapi.hangout.data.submitDelta( delta );
    //addedResults(resultKey, words);
}

function firstPlayerSetup() {
    clearResults();

    letters = populateLetters();
    gapi.hangout.data.submitDelta( {letters: JSON.stringify(letters)} );
    //populateBoard();
    //startTimer();
    //displayBoard();
}

(function() {
    if (gapi && gapi.hangout) {

        console.log('app is loading');

        var initHangout = function(apiInitEvent) {
            if (apiInitEvent.isApiReady) {
                console.log('initializing');

                gapi.hangout.data.onStateChanged.add(stateChanged);
                gapi.hangout.onParticipantsChanged.add(function(partChangeEvent) {
                    updateLocalParticipantsData(partChangeEvent.participants);
                });

                if (!state_) {
                    var state = gapi.hangout.data.getState();
                    var metadata = gapi.hangout.data.getStateMetadata();
                    if (state && metadata) {
                        state_ = state;
                        metadata_ = metadata;
                    }
                }
                if (!participants_) {
                    var initParticipants = gapi.hangout.getParticipants();
                    if (initParticipants) {
                        updateLocalParticipantsData(initParticipants);
                    }

                    //if (initParticipants.length == 1) {
                        //console.log('your the first player');
                        //firstPlayer = true;

                        document.getElementById('startDiv').style.display = 'block';
                    //}
                }

                gapi.hangout.onApiReady.remove(initHangout);

            }
        };

        document.addEventListener('timerExpired', gameEnd);

        gapi.hangout.onApiReady.add(initHangout);
    }
})();
